<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------
require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
class KeywordAction extends NewzanAction
{
	/** @var AutoDriveBaseModel */
	private $_autoDriveMdl = null;

    private static $source = array(
                0 => 'summary',
                1 => 'pc',
                2 => 'wireless'
            );

     public function _initialize()
	{
		parent::_initialize();
		$this->userId = $this->me['user_id'];
		// self::$p = array(
		// 	'start_date' => date('Y-m-d', strtotime('-7 day')),
		// 	'end_date' => date('Y-m-d', strtotime('-1 day'))
		// );
		$this->http = new Curl();
	}

    public function savekeyword(){
        $json = $_POST["json"];
        $data = json_decode($json , true);
        $myKewordMdl = M('mykeyword');
        $result = array();
        foreach($data["keywords"] as $w){
            $whr = array(
                'word' => $w["word"],
                'user_id' => $this->me['user_id']
            );
            $keyword = $myKewordMdl->where($whr)->find();
            
            if(!$keyword){
                $keyword = array(
                    'word' => $w["word"],
                    'user_id' => $this->me['user_id'],
                    'category_id' => $data['params']['category_id'],
                    'campaign_id' => $data['params']['campaign_id'],
                    'adgroup_id' => $data['params']['adgroup_id'],
                    'max_price' => getPriceofCent($w["price"]),
                    'addtime' => date('Y-m-d H:i:s')
                );
                $kid = $myKewordMdl->add( $keyword );
            }
            
            $result[] = array(
                'word' => $keyword["word"],
                'max_price' => $keyword["max_price"],
                'keyword_id' => $kid ? $kid : 0
            );

        }
        $this->display_json( array("result" => true , "keywords" => $result)  );
    }
    
    public function deletemine(){
    	$keyword = $this->_post('keyword');
    	ParamsCheckUtils::checkNULL($keyword , '删除备选关键词时参数错误');
    	$myKewordMdl = M('mykeyword');
    	$result = array();
    	$whr = array(
			'word' => $keyword,
			'user_id' => $this->me['user_id']
    	);
 		$ret = $myKewordMdl->where($whr)->delete();
    	$this->display_json( array("result" => true , "keyword" => $keyword)  );
    }
    
    
    
    public function boundary(){
        $cid = $this->_get("category_id");
        $type = $this->_get("type");
        $boundary = null;
        if($cid){
        	import("@.Library.Carine");
        	$carine = new Carine();
        	$boundary = $carine->getBondary($cid);
        }
        
        if(!$boundary){
            $boundary = array(
                'avg_price' => array( "min" => 0 , "max" => rand(100,500) ), 
                'pv' => array( "min" => 0 , "max" => 10000), 
                'click' => array( "min" => 0 , "max" => 100000), 
                'ctr' => array( "min" => 0 , "max" => rand(1000 ,2000) ), 
                'competition' => array( "min" => 0 , "max" => 10000)
            );
        }
        
        if( (int) $boundary['avg_price']['max'] > 5000 ){
            $boundary['avg_price']['max'] = 5000;
        }                

        if( (int) $boundary['ctr']['max'] > 10000 ){
            $boundary['ctr']['max'] = 10000;
        }                
        
        $this->display_json($boundary);
    }
    
    
    public function add(){
        $json = $_POST["json"];
        //$json = rawurldecode($json);
        $data = json_decode($json , true);
        //analyze the params 
        
        //get adgroup id and campaign_id
        
        $adgroup_id = $data["params"]["adgroup_id"];
        //$campaign_id = $data["params"]["campaign_id"];
        

        $user_id = $this->me['user_id'];
        $adgroupMdl = D('Adgroup');
        // check parameters
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
        if(!$adgroup) {
        	$this->display_json(array('result'=>false, 'msg'=>'推广组不存在.'), RetStatus::INNER_ERR);
        }
        
        $keywordMdl = D("Keyword");
        $result = array();
        $keywords = array();
        foreach($data["keywords"] as $w){
            $keywords[] = array(
                'max_price' => getPriceofCent($w["price"]),
                'matchscope' => 4,
                'word' => $w["word"]
            );
        }
           
        try{
            $result = $keywordMdl->addKeywords($this->me['user_id'] , $adgroup_id , $keywords);
            
            $added_keywords = array();
            foreach($result as $k => $r){
            	$added_keywords[] = array(
            			'keyword_id' => $r['keyword_id'],
            			'word' => $k,
            	);
            }
            $this->display_json( array("result" => true , "keywords" => $added_keywords) );
            
        }catch(Exception $e){
            //TODO, 出错时的处理
            // 1. 关键词价格原因(不能低于5) 2.其他原因
            //{"error_response":{"code":15,"msg":"Remote service error","sub_code":"isv.invalid-parameter","sub_msg":"没有有效关键词可增加， 输入的关键词和已有出现重复"}}
//             $result = array();
//             foreach($data["keywords"] as $w){
//                 $result[$w["word"]] = array(
//                     'keyword_id' => 0,
//                     'word' => $w["word"]
//                 );
//             }
			$msg = '内部错误';
            if($e instanceof TopClientException) {
            	$topErrMsg = json_decode($e->getMessage(), true);
            	$msg = $topErrMsg['error_response']['sub_msg'];
            }
            $this->display_json( array("result" => false , "msg" => $msg), RetStatus::TOP_API_ERR);
        }
        
    }
    
    public function helper(){
        $this->display();
    }
    
    // 获取某个关键词的预测信息（排名，流量，消耗等)
    public function forcast(){
    	$keyword_id = $this->_get('keyword_id');
    	$price = $this->_get('price');
    	if($price<10)//peice小于0.1会出错
    		$price=10;
    	ParamsCheckUtils::checkNumeric($keyword_id);
    	
    	$keywordMdl = new KeywordModel();
    	// keyword有可能被删除了。被删除的词只显示最近的淘宝统计数据，没有预测数据。
    	$keyword = $keywordMdl->where(array('keyword_id'=>$keyword_id))->find();
    	$del = false;
    	if(!$keyword) { // 如果不在keywords表中，查询是否已被删除
    		$keyword = $keywordMdl->getDelWord($keyword_id);
    		$del = true;
    	}
    	if(!$keyword) // 还是不存在，则抛出异常
    		throw new NewzanException('关键词不存在。');
    	
    	$forcast_info = array();
    	if(!$del) {
	    	$cache = Cache::getInstance('File');
	    	$cache_key = $keyword_id . $price . "forcast";
	    	$data = $cache->get($cache_key);
	  
	    	if(!$data){	    		    	
		    	$respObject = $keywordMdl->forecastWord($keyword_id, $price);
		    	$forcast_info = (array) $respObject['keyword_forecast'];
		    	$cache->set($cache_key , json_encode($forcast_info));
	    	}else{
	    		$forcast_info = json_decode($data , true);
	    	}
	    	$forcast_info['matchscope']= $keyword['matchscope'];
    	}
    	
    	$result = array(
    			'keyword_id' => $keyword_id,
    			'max_price' => $price,
    	        'nick' => $keyword['nick'],
    	        'word' => $keyword['word'],
    			'matchscope' => $keyword['matchscope'],
    			'forcast' => array(
    					'price_rank' => array(), 
    					'price_cust' => array(), 
    					'price_click' => array() ),
    			'current' => array(
    					'price_rank' => array(),
    					'price_cust' => array(),
    					'price_click' => array() ),
    	);
    	
	    if(!$del) {
	    	foreach( $result['forcast'] as $key => $v){
	    		$series = array();
	    		foreach( explode(',', $forcast_info[$key]) as $tmp){
	    			$tmp_arr = explode(':' , $tmp);
	    			if( count($tmp_arr) ==2 ){
	    				list($x,$y) = $tmp_arr;
	    				$series[] = array( (int)$x , (int)$y);    				
	    			}else{
	    			}
	    		}
	    		$result['forcast'][$key] = $series;
	    	}
	    	
	    	//得到目前价格下的预测信息显示
			foreach( $result['forcast'] as $key => $value ){
				$closest_point = null;
				foreach($value as $point){
					if( !$closest_point || abs( $point[0] - $price ) <  abs($closest_point[0] - $price) ){
						$closest_point = $point;
					}
				}
				$result['current'][$key] = $closest_point[1];
			}
    	}
			
    	
    	//得到关键词的全网统计属性
    	$wordMdl = new WordModel();
    	$stat = $wordMdl->getAvgProps( $keyword['word'], 'pv,click,ctr,competition,avg_price');
    	$series = $wordMdl->getSerialProps( $keyword['word'], 'pv,click,ctr,competition,avg_price');
    	$series = array_pop ( $series );
    	$series_keys = array(
    	        'pv' , 'click' , 'ctr' , 'competition', 'avg_price'
     	);
    	$series_str = array();
    	foreach( $series_keys as $k){
    	    $series_str[$k] =  array_column($series, $k);
    	}
    	$result['stat'] = array_pop($stat);
    	$result['series'] = $series_str;
		$this->display_json( $result );
    	
    }
    
	/**
	 * 获取某个类目出价的预测信息（排名，流量，消耗等)
	 */ 
    public function forcastcat(){
    	$adgroup_id = $this->_get('adgroup_id');
    	$price = $this->_get('price');
    	
    	$cache = Cache::getInstance('File');
    	$cache_key = $adgroup_id . $price . "forcastcat";
    	$data = $cache->get($cache_key);
    	if(!$data){	    	
	    	$keywordMdl = new KeywordModel();
	    	$respObject = $keywordMdl->forecastCat($adgroup_id, $price);
	    	$forcast_info = (array) $respObject['adgroup_catmatch_forecast'];
	    	$cache->set($cache_key , json_encode($forcast_info));
    	}else{
    		$forcast_info = json_decode($data , true);
    	}
    	
    	$result = array(
    			'adgroup_id' => $adgroup_id,
    			'max_price' => $price,
    	        'nick' => $forcast_info['nick'],
    	        'word' => $forcast_info['word'],
    			'forcast' => array(
    					'price_rank' => array(), 
    					'price_cust' => array() , 
    					'price_click' => array()
    					)
    	);
    	
    	foreach( $result['forcast'] as $key => $v){
    		$series = array();
    		foreach( explode(',', $forcast_info[$key]) as $tmp){
    			list($x,$y) = explode(':' , $tmp);
    			$series[] = array( (int)$x , (int)$y); 	
    		}
    		$result['forcast'][$key] = $series;
    	}
    	
		$this->display_json( $result );
    }
    
    /**
     * 得到关键词的当前排名
     */
    public function rank()
    {
        $condition['keywords'] = $this->_post('kids');
        $condition['product_id'] = $this->_post('product_id');
        if($this->_post('adgroup')) {
            $condition['adgroup'] = true;
        }
        $keywords = R('Keyword/keywordsRealRank', array($condition), 'Event');
        $this->display_json(array(
                                    'result' => true,
                                    'ranklists' => $keywords
                                )
                            );
    } 
    
    public function addrows(){
        $json = $_POST['json'];
        
        $data = json_decode($json, true);
        
        $params = $data["params"];
        
        $tpl = $params["action"];
        
        $kids = $data['keywords'];
        if(!count($kids)) $this->error("参数缺");
        
        $keywordMdl = D('Keyword');
        $keywords = $keywordMdl->getKeywords($user_id , $kids);
        foreach($keywords as &$w){
            $w = array_merge($w , 
                    array(
                    'pv' => rand(100000,10000000),
                    'click' =>  rand(100000,10000000),
                    'width' => rand(50,100),
                    'avg_price' => round( rand(20,100) / 100.0 , 2),
                    'ctr' => rand(10,50) / 100.0,
                    'cpc' => rand(50,200) / 100.0,
                    )
                );
        }
        $this->keywords = $keywords;
        $this->display( "tr_" . $tpl);
    }
    
    public function campaign(){
        $json = $_POST['json'];
        $data = json_decode($json, true);
        $params = $data["params"];
        //if adgroup_id is set , and retieve keywords by adgroup_id or by campaign_id , or by user_id
        $keywords = null;
        $keywordMdl = D("Keyword");
        $keywords = $keywordMdl->getCampaignKeywords($this->me["user_id"] , $params["campaign_id"] , $params);
        $keywords = $this->getKeywordsStats($keywords);
        $adgroupMdl = D("Adgroup");
        $adgroups = $adgroupMdl->getCampaignsAdgroups($this->me['user_id'], $params["campaign_id"]);
        $adinfo = array();
        
        foreach($adgroups as $ad){
            $adinfo[$ad["adgroup_id"]] = $ad;
        }
        
        foreach($keywords as $ix => $k){
        	if( isset( $adinfo[$k["adgroup_id"]] ) ){
	            $k["img_url"] = $adinfo[$k["adgroup_id"]]["img_url"];
	            $k["title"] = $adinfo[$k["adgroup_id"]]["title"];
	            $k['has_ad'] = true;
        	}else{
        		unset($keywords[$ix]);
        	}
        }
        
        $this->keywords = $keywords;
        $this->display('manager');
    } 
    
    /**
     * 一键智能填词
     */
    public function autowords(){
        require_once LIB_PATH . "Library/TaobaoAPI/Curl.php";
        $adgroup_id = intval( $this->_post('adgroup_id') ) ;
        ParamsCheckUtils::checkNumeric( $adgroup_id , '必须输入推广组的id' );
        $type = intval( $this->_post('type') ) ;
        $type = ($type == 1 || $type == 2)  ? $type  : 1;
        $curl = new Curl();
        $url = build_url("sinbadgateway/users/{$this->me['user_id']}/adgroups/{$adgroup_id}/@autoWords", array('device'=> $type));
        $resp = $curl->get($url);
        $resp = object_to_array($resp->keywords);
        $this->display_json( array('keywords' => $resp));
    }
    
    public function manager(){
        $adgroupMdl = new AdgroupModel();
        $params = $_POST;

         //获取当天的质量得分数据
         $user_id = $this->me['user_id'];
        $test = 'rpt_keyword'.$user_id;
        $dataMdl = M($test);
        $where['date'] = date('Y-m-d');
        $where['adgroup_id'] = $params['adgroup_id'];
        $most = $dataMdl->where($where)->Field('keyword_id')->select();
        foreach ($most as $key=>$values){
            $where1['keyword_id'] = $values['keyword_id'];
            $where1['date'] = date('Y-m-d');
            $result1= $dataMdl->where($where1)->Field('wireless_qscore')->find();
            $re[$values['keyword_id']] = $result1['wireless_qscore'];
         }
        //获取昨天的质量得分数据
         $where2['date'] = date('Y-m-d',strtotime('-1day'));
          $where2['adgroup_id'] = $params['adgroup_id'];
         $mast = $dataMdl->where($where2)->Field('keyword_id')->select();
                
        foreach($mast as $k=>$val){
             $where3['keyword_id'] = $val['keyword_id'];
             $where3['date'] = date('Y-m-d',strtotime('-1day'));
             $result2 = $dataMdl->where($where3)->Field('wireless_qscore')->find();
             $res[$val['keyword_id']] = $result2['wireless_qscore'];
         }
        //今天与昨天的数据进行比较
        foreach ($re as $key=>$values){
            if($values<0){
                $values = 0;
                continue; 
             }else{
                 if($values>$res[$key]){
                        $new[$key] = '1';
                  }else{
                     $new[$key] = '0';
                 }
             }         
         }
        $this->comparative_result = $new;
        
        $sourceType = (isset($params['platform']) && in_array($params['platform'], array(0,1,2)))? self::$source[$params['platform']] : self::$source[0] ; // 0 summary , 1 pc , 2 wireless
        //if adgroup_id is set , and retieve keywords by adgroup_id or by campaign_id , or by user_id
        $keywords = null;
        $keywordMdl = new KeywordModel();
        $user_id = $this->me['user_id'];
        $tpl = '';
        $keywords = array();
        $sortType = $params['desc'] == 'true' ? 'desc' : 'asc';
        $filters = $params['filter'];
        $pageSize = $params['pageSize'];
        $currentPage = $params['currentPage'];
        // 记录选择的时间
        $skName = "{$params['action_type']}_time{$user_id}-{$params['adgroup_id']}";
        session($skName, array(
                            'from'=> $params['from'],
                            'to' => $params['to']
                        )
                    );

        foreach( $filters as $k => $f){
        	if( empty( $f ) || ($f['max'] == 0 && $f['min'] == 0)) {
        		unset($filters[$k]);
        		continue;
        	}
        	
        	switch($k){
        		
        		case 'price':
                    if(is_array($f)) {
                        $filters['max_price']['max'] = $f['max'];
                        $filters['max_price']['min'] = $f['min'];
                    } else {
                        $filters['max_price'] = $f;
                    }
                    unset($filters['price']);
        		break;
                case 'mobile_price':
                    if(is_array($f)) {
                        $filters['max_mobile_price']['max'] = $f['max'];
                        $filters['max_mobile_price']['min'] = $f['min'];
                    } else {
                        $filters['max_mobile_price'] = $f;
                    }
                    unset($filters['mobile_price']);
                    break;
        		
        		case 'cpc':
        		case 'cpm':
        		case 'ctr':
        		case 'cvr':
        		default:
                $filters[$k]['eq'] = true;
                break;

        		
        	}
        	
        } 
        
		$word = $params['word'];
		if( $word ){
			$filters['word'] = $word;
		}        
        if($params['adgroup_id']) {
            if($params['sort'] == 'ravgpos') {
                $this->hide = false;
            } else {
                $this->hide = true;
            }
            $tpl = 'manager';
        	
        	$t = false;
            if(in_array($params['sort'], array('q_impressions','q_cvr','q_cpc','q_roi','q_competition'))) {
                $t_sort = $params['sort'];
                $params['sort'] = 'impressions';

                $t = true;
            }
        	$keywords = $keywordMdl->getKeywordsWithStats('adgroup_id', $params['adgroup_id'],
        			$params['from'] ,  $params['to'], $params['sort'], $sortType,
        			$params['currentPage'], $params['pageSize'] ,$filters, false, false, $sourceType
        			);
            if($keywords) {
                $adgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $params['adgroup_id']);
                $mobile_discount = floatval($adgroup['mobile_discount']/100);
                foreach ($keywords as $key => &$keyword) {
                    if((int)$keyword['mobile_is_default_price'] === 1) {
                        $keyword['max_mobile_price'] = floatval(($keyword['max_price'] * $mobile_discount)/100);
                    } else {
                        $keyword['max_mobile_price'] = price_display_str($keyword['max_mobile_price']/100);
                    }
                    $keyword['a_title'] = $adgroup['title'];
                    $keyword['img_url'] = $adgroup['img_url'];
                    $keyword['num_iid'] = $adgroup['num_iid'];
                }
            }

            $this->action_keywords = S("action_keywords_{$user_id}");

            // 获取全网市场数据
            if(isset($params['marketdata'])) {
                $s_name = 'marketdata_'.$user_id;
                
                // $marketdata = session("?$s_name") ? session("$s_name") : array();
                if(session("?{$s_name}")) {
                    $marketdata = session("{$s_name}");
                } else {
                    $tmp_marketdata = array();
                    foreach ($keywords as $key => $word) {
                        $tmp_marketdata[$key]['keyword_id'] = $word['keyword_id'];
                        $tmp_marketdata[$key]['word'] = $word['word'];
                    }
                    $marketdata = $this->getMarket($tmp_marketdata, $params['from'], $params['to']);
                }
                if($marketdata) {
                    $kiids = array_keys($marketdata);
                    foreach ($keywords as $key => $word) {
                        if(in_array($word['keyword_id'], $kiids)) {
                            $keywords[$key]['q_impressions'] = (int)$marketdata[$word['keyword_id']]['effect']['impression'];   // 展现量
                            $keywords[$key]['q_cvr'] = floatval($marketdata[$word['keyword_id']]['effect']['coverage']);        // 点击转化率
                            $keywords[$key]['q_cpc'] = floatval($marketdata[$word['keyword_id']]['effect']['cpc']);             // 平均点击花费
                            $keywords[$key]['q_roi'] = floatval($marketdata[$word['keyword_id']]['effect']['roi']);             // 投入产出比
                            $keywords[$key]['q_competition'] = (int)$marketdata[$word['keyword_id']]['effect']['competition'];  // 竞争度
                        }
                    }
                }
                if($t) {
                    usort($keywords, "uc_cmp_{$t_sort}" . "_{$sortType}");
                }
            } else {
                $params['marketdata'] = false;
            }
            $this->show_marketdata = $params['marketdata'];

            $this->platform = $sourceType;



        } elseif($params['campaign_id']) {
        	$tpl = 'campaign';
        	$keywords = $keywordMdl->getKeywordsWithStats('campaign_id', $params['campaign_id'],
        			$params['from'] ,  $params['to'], $params['sort'], $sortType,
        			$params['currentPage'], $params['pageSize'] , $filters);
        } else { // user
        	$this->error('不支持的参数.');
        }
        $nonkeywords=array();

        //如果是第一页的话获取特殊位置的关键词统计报表，类目出价和定向推广的
        if( $params['adgroup_id'] && $params['currentPage'] == 1 ){
        		$nonkeywords = $keywordMdl->getSpecialKeywordsStats($user_id, 'adgroup_id' ,$params['adgroup_id'] , 
                                                    $params['from'] ,  $params['to']);
			foreach($nonkeywords as $ix => &$k){
           		if($ix==9){
           			// $adgroupMdl = new AdgroupModel();
           			$catmatch = $adgroupMdl->getAdgroupCatMatch($user_id, $params['adgroup_id']);
           			$k['online_status']=$catmatch['online_status'];
           			$k['max_price']=$catmatch['max_price'];
           		}
           		$k['keyword_id']=$ix;
               $k['word'] = $ix == 9 ? '类目出价' : '定向投放';
               
               $k['qscore'] = 0;
               $k['matchscope'] = 0;
               $k['avgpos'] = isset($k['avgpos']) ? $k['avgpos'] : 0;
			}
           
           	if(session('admin')) { // 如果是管理员，显示近期删除的关键词
                $this->del_keywords = array();
           	}
        }

        // 给关键词加上adgroup信息
        if($params['campaign_id']) {
        	$adgroups = $adgroupMdl->getCampaignsAdgroups($user_id, $params['campaign_id']);
        	$adinfo = array();
        	foreach($adgroups as $ad){
        		$adinfo[$ad['adgroup_id']] = $ad;
        	}
        	foreach($keywords as $ix => $k){
        		if( isset(  $adinfo[$k['adgroup_id']] ) ){
	        		$keywords[$ix]['img_url'] = $adinfo[$k['adgroup_id']]['img_url'];
	        		$keywords[$ix]['title'] = $adinfo[$k['adgroup_id']]['title'];
	        		$keywords[$ix]['has_ad'] = true;
        		}else{
        			unset( $keywords[$ix] );
        		}
        	}
        }
        $keywords = array_merge($nonkeywords , $keywords);
        $this->keywords = $keywords;
        $this->adgroupId=$params['adgroup_id'];
        $is_admin = session('admin');
        $this->is_admin = $is_admin  ? true : false;
        $this->display($tpl);
    }
    
    public function remove(){
        $json = $_POST['json'];
        $data = json_decode($json, true);
        
        $params = $data["params"];
        $keywordMdl = D("Keyword");
        $keywords = array();
        
        $adgroupMdl = D('Adgroup');
        $adgroup_id = $params['adgroup_id'];
        
        $user_id = $this->me['user_id'];
        
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
        if(!$adgroup) {
        	$this->display_json(array('result'=>false, 'msg'=>'推广组不存在.'), RetStatus::INNER_ERR);
        }
        
        
        if($params["campaign"] == 0){
            $params['campaign_id'] = $adgroup['campaign_id'];
        }
        
        $result = array();
        foreach($data["keywords"] as $kid => $w ){
            if($w["selected"] && $kid > 0){
                $keywords[$w['word']] = $kid;
            }else{
                if($w["selected"]){
                    M("keywords")->where("keyword_id = " . $kid)->delete();
                    $result[$kid] = array(
                  		'status' => "deleted",
                        'keyword_id' => $kid,
                        'action' => 'delete'                      
                    );
                }
            }
        }
        
        if(count($keywords)){
            $resp = $keywordMdl->deleteKeywords($keywords , $params['campaign_id']);
        }
        foreach($resp as $r){
            $result[$r["keyword_id"]] = array(
                'status' => "deleted",
                'keyword_id' => $r["keyword_id"],
                'action' => 'delete'
            );
        }
                
        $this->display_json(  array( "keywords" => $result , "params" => $params) );
    }
    
    public function setting(){
    
    }
    
    /**
     * 更改关键词出价等
     */
    public function update(){
        $keywords = $_POST["keywords"];
        $keywordMdl = new KeywordModel();
        $params = $_POST['params'];
        $adgroup_id = $params['adgroup_id'];
        
        $user_id = $this->me['user_id'];

        $update_keywords = array();
        $delete_keywords = array();
        $add_keywords = array();
        $word_okid_map = array();
        $result = array();
        
		// check parameters
		$apiMdl = new ApiModel();
		$adgroupMdl = new AdgroupModel();
        $adgroup = $adgroupMdl->getAdgroupByAdgroupId($user_id, $adgroup_id, false);
        if(!$adgroup) {
        	$this->display_json(array('result'=>false, 'msg'=>'推广组不存在.'), RetStatus::INNER_ERR);
        }

        // 如果是管理员登录(在上面判断了)，才允许手动修改自动开车的关键词
        $isAutoDrive = $adgroup['drive_type'] == AdgroupModel::DRIVE_TYPE_AUTO; 
        
        
        foreach($keywords as $kid => $w){
        if($kid==9){
		        $catmatch_price = $w['new_price'];
		        $existentCatmatch = $adgroupMdl->getAdgroupCatMatch($user_id, $adgroup_id); // TODO 这里虽然调用了API, 是否一定会返回?
		        if($existentCatmatch['online_status']=='online') {
			        $params = array(
			            'adgroup_id' => $adgroup_id,
			            'catmatch_id' => $existentCatmatch['catmatch_id'],
			            'max_price' => $catmatch_price,
			            'use_default_price' => "false",
			            'online_status' => $existentCatmatch['online_status']
			        );
			        
		        	$currSucc = $adgroupMdl->updateAdgroupCatMatch($user_id , $params, $isAutoDrive);
		        	if($currSucc) {
		        		$result[ strval($kid) ] = array(
                		'status' => "adjusted",
                		'keyword_id' => $kid,
                		'action' => 'adjust',
                		'price' => $catmatch_price,
            			);
		        	}
		    	}
        }else{
        	
        	switch( $w['action'] ){
        		
        		//调价
        		case 'adjust' :
        			//set price
        			$new_price = isset($w['new_price']) ? $w['new_price'] : $w['price'];
        			$old_price = $w['price'];
                    $new_mobile_price = isset($w['new_mobile_price']) ? $w['new_mobile_price'] : $w['mobile_price'];
                    $old_mobile_price = $w['mobile_price'];
        			if( $new_price != $old_price || $new_mobile_price != $old_mobile_price || (isset($w['new_matchscope']) && $w['new_matchscope'] != $w['machescope'])){
        				$update_keywords[$kid] = array(
    						'word' => $w['word'],
    						'max_price' => $new_price,
    						'matchscope' => isset($w['new_matchscope'])?$w['new_matchscope']:$w['machescope'],
    						'keyword_id' => $kid
        				);

                        if((int)$w['default_mobile_price'] === 0) {
                            $update_keywords[$kid]['mobile_is_default_price'] = 0;
                            $update_keywords[$kid]['max_mobile_price'] = $new_mobile_price;
                        }
        			}
        		break;
        		
        		case 'delete':
        			if($kid > 0){
        				$delete_keywords[$w['word']] = $kid;
        			}else{
        				//TODO , 这个方法应该在model中处理好
        				//if not on api then just delete it on local storage
        				M("keywords")->where("keyword_id = " . $kid)->delete();
        				$result[$kid] = array(
        						'status' => "deleted",
        						'keyword_id' => $kid,
        						'action' => 'delete',
        				);
        			}       			
        		break;
        		
        		
        		case 'add':
        			$add_keywords[] = array(
                            'mobile_price' => isset( $w['mobile_price'] ) ? $w['mobile_price'] : $w['mobile_price'],
        					'max_price' => isset( $w['price'] ) ? $w['price'] : $w['price'],
                            'matchscope' => isset( $w['matchscope'] ) ? $w['matchscope'] : 4,
        					'default_mobile_price' => (isset($w['default_mobile_price']) && ((int)$w['default_mobile_price'] == 1 || (int)$w['default_mobile_price'] == 0)) ? (int)$w['default_mobile_price'] : 0,
        					'word' => $w["word"]
        			);
        			$word_okid_map[$w['word']] = $kid;
        		break;
        		
        	}

            //set add keywords
        }
        }

        if($params["campaign_id"] == 0){
            $params['campaign_id'] = $adgroup['campaign_id'];
        }

        if(count($delete_keywords)){
            $resp = $keywordMdl->deleteKeywords($delete_keywords , $params['campaign_id'], $apiMdl, $isAutoDrive);
        }
        
        foreach($resp as $r){
            $result[ strval( $r["keyword_id"] ) ] = array(
                'status' => "deleted",
                'keyword_id' => $r["keyword_id"],
                'action' => 'delete',
            );
        }
        
        unset($resp);
        
        if ( count($update_keywords) ){
            $resp = $keywordMdl->updateKeywords($adgroup_id , $update_keywords, $apiMdl, $isAutoDrive);
        }
        
        foreach($resp as $k=>$r){
            $result[ strval($r["keyword_id"]) ] = array(
                'status' => "adjusted",
                'keyword_id' => $r["keyword_id"],
                'action' => 'adjust',
                'price' => $r['price'],
            	'word' => $k,
            	'matchscope' => $r['matchscope'],
                'mobile_is_default_price' => $r['mobile_is_default_price'],
                'max_mobile_price' => $r['max_mobile_price']
            );
        }
        
        unset($resp);

        if( count($add_keywords) ){
        	$resp = $keywordMdl->addKeywords($this->me['user_id'] , $adgroup_id , $add_keywords, $apiMdl, $isAutoDrive);
        	foreach($resp as $k => $r){
        		$result[ strval( $word_okid_map[$k] ) ] = array(
        				'action' => 'add',
        				'status' => 'added',
        				'keyword_id' => $r['keyword_id'],
        				'word' => $k,
        		);
        	} 
        	
        }

        if($result) {
            import('@.Library.KeywordCache');
            $keywordCache = new KeywordCache($user_id, $result, $keywords);
            $keywordCache->handle();
        }
        
        $this->display_json(  array( "keywords" => $result , "params" => $params) );
    }
    
    protected function keywordFilter($params){
        import("@.Library.Carine");
        $carine = new Carine();
        $filter = array();
        foreach($params['filter'] as $k => $f){
            $min = $k == 'ctr'  ?  $f['min'] / 1000.0 :  $f['min'];
            $max = $k == 'ctr'  ?  $f['max'] / 1000.0 :  $f['max'];
            $filter[] = array(
                'field' => $k, 
                'min' => $min,
                'max' => $max
            );
        }
        $service_params = array(
            'mykeywords' => $params["mykeywords"],
            'cate_id' => $params["category_id"],
            'is_not' => $params["filterType"],
            'page' => $params["currentPage"],
            'pagesize' => $params["pageSize"],
            'filters' => json_encode($filter),
            'order' => $params['sort'],
            'asc' => $params['desc'] == 'true' ? 'false' : 'true',
        	'timespan' => 'WEEK',
        );
        $res = $carine->getFilterWords($service_params);
        $result = json_decode($res, true);
        if($result["status"] != 200){
            return array();
        }else{
            $recommend_words = $result["response"]["keywords"];
            return $recommend_words;
        }
        
    }

    //关键词未同步手动触发
    public function getData(){
        $user_id = $this->me['user_id'];
        $adgroup_id =$_POST['adgroup_id'];
          $getadgroup = array(
                'adgroup_id' =>$adgroup_id,
          );
        $url_getadgroup = build_url( "sinbadgateway/users/{$user_id}/adgroups/{$adgroup_id}/@manualsync");
        $this->http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        $test = $this->http->get($url_getadgroup);
    }

    /**
     * 智能推荐词
     * 
     * @param array(k=>v) $params
     * @throws NewzanException
     * @return array
     */
    protected function keywordSmart($params){
        $category_id = $params["category_id"];
        $data_duration = $params["dataDuration"];
        $default_price = $params["default_price"];
        $price_mode = $params["priceMode"];
        $price_set = $params["priceSet"];
        $rec_type = $params["searchMode"];
        $order = $params['sort'];
        $desc = $params['desc'];
        $mykeywords = $params["mykeywords"];
        $num = $params["pageSize"];
        $adgroup_id = $params['adgroup_id'];
        $device=(int)$params['device'];
        //get creative titles if mykeywords = null,
        $content = '';
        // $creativeMdl = D('Creative');
        // $creatives = $creativeMdl->getCreativesByAdgroupId($this->me["user_id"] , $adgroup_id);
        // foreach($creatives as $c){
        //     $content .= " " . $c["title"];
        // }
        
        // $adgroupMdl = new AdgroupModel();
        // $adgroup = $adgroupMdl->getAdgroupByAdgroupId( $this->me['user_id'], $adgroup_id);
        // if( !$adgroup ){
        //     throw new NewzanException( '指定的推广组不存在或者被删除了' , RetStatus::PARAM_ERR);
        // }
        // $content .= "" . $adgroup['title'];
        
        $recType = array(
        		'#hot' => 1,
        		'#related' => 2,
        		'#combination' => 3
        );
        
        import("@.Library.Carine");
        $carine = new Carine();
        $opts = array(
           'maxPrice' => $default_price,
            'sort' => $order,
            'direction' => $desc == 'true' ? 'desc' : 'asc',
            'defaultPrice' => $params["default_price"],
        	'mode' => $price_mode, 
            'device'=>$device,
            'adgroup_id'=>$adgroup_id,
        );
        $url = build_url("lexiconservice/adgroups/{$adgroup_id}/recommends", $opts);
        $this->http->setOpt(CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        $result =$this->http->get($url);
       return $result;
    }
    
    /**
     * 词操作分发器
     */
    public function recommend(){
        $params = $_POST;
        $params['mykeywords'] = is_array($params['mykeywords']) ? zh_arrtolower($params['mykeywords']) : zh_strtolower($params['mykeywords']); // 确保进入系统的词都用小写字母
        $params['user_id'] = $this->me['user_id'];
        $this->mode = $params["searchMode"];
        
        $recommend_words = array();
        switch($params["searchMode"]){
            case "#filter":                     // 海量淘词
                $recommend_words = $this->keywordFilter($params);
           	 	break;
            case '#manual':                     // 手动加词
               $recommend_words = $this->manualKeywords($params);
            	break;
            case "#mykeywords":                 // 我的词库
                $recommend_words = $this->findMyKeywords($params);
            	break;
            case "#related":                    // 相关性选词
                $recommend_words = $this->findRelatedKeywords($params);
            	break;
            case "#copy":                       // 复制词
                $recommend_words = $this->copyKeywords($params);
           	 	break;
            case "#combination":                // 组合选词
                $recommend_words = $this->combineKeywords($params);
            	break;
            case "#smart":                      // 智能选词
            default :
                $recommend_words = $this->keywordSmart($params);
           	 	break;
        }

          $result = object_to_array( $recommend_words);
        $invoke_failure = false;
        $record_not_found = false;
            if($result['status'] == 500){
                $invoke_failure = true;
                if($result['message'] == 'record_not_found') {
                   $record_not_found = true;
                }
                $recommend_words = array();
                $this->ad_id = $params['adgroup_id'];
            } else {
                if($params['device'] >=3){
                    $data = array();
                    $test =array(
                        'a'=>'mobile',
                        'b'=>'hot',
                        'c'=>'precise',
                        'd'=>'promote'
                    );
                    foreach ($result as $values){
                        if(isset($values['tag_name'])){
                                foreach ($values['tag_name'] as $vs){
                                    if($vs == $test[a] && $params['device'] == 3){
                                            $data[] = $values;
                                        } else if($vs == $test[b] && $params['device'] == 4){
                                            $data[] = $values;
                                        }else if($vs == $test[c] && $params['device']== 5){
                                            $data[] = $values;
                                        }else if($vs == $test[d] && $params['device']==6){
                                                $data[] = $values;
                                        }
                                }
                        }
                    }
                    $result = $data;
                } 
                $recommend_words = $result;
            }
            $this->words = $recommend_words;
            $this->failure = $invoke_failure;
            $this->record_not_found = $record_not_found;
            $this->words_count = count($recommend_words);
            $this->display();
        
             exit;
        // 分页和排序. 智能推荐和海量淘词已经分页和排序了，无需再操作 #去除分页 By Leepuman 2015/6/24
        if( $params["searchMode"] != '#smart' && $params['searchMode']  != '#filter'){
           $order = $params['sort'];
           $asc = $params['desc'] == 'true' ? false : true;
           if(!empty($order)) {
               $orderMethod = "uc_cmp_$order" . '_' . ($asc ? 'asc' : 'dec');
               usort($recommend_words, $orderMethod); // 自定义排序的方法定义在 Application/Common/common.php中.
           }
        #    $page = $params['currentPage'];
        #    $pageSize = $params['pageSize'];
        #    $pageStart = ($page - 1) * $pageSize;
        #    $recommend_words = array_slice($recommend_words, $pageStart, $pageSize);
        }

        // 参考出价
        $price_mode = intval($params["priceMode"]); // .'mode';
        $price_set = $params["priceSet"]; // $price_mode == 0 时使用
        $price_types = AutoDriveBaseModel::$PRICE_TYPES;

        // 如果是三种自动出价模式之一，调用AutoDriveBaseModel()出价
        $wordsPrice = array();
        if($price_mode > 0) {
        	if($params["searchMode"] == '#smart') { // 智能选词已经设定价格了
				foreach ($recommend_words as $wordStatPrice) { // 原来的词没有用$word作为主键, 所以需要copy一遍.
					$wordsPrice[ $wordStatPrice['word'] ] = array(
							'word' => $wordStatPrice['word'], 
							'max_price' => $wordStatPrice['max_price'] 
					);
				}
        	} else { // 其他需要专门调用服务来设定价格
	        	$autoDriveMdl = new AutoDriveBaseModel();
	    		$wordsPrice = $autoDriveMdl->init($params['adgroup_id'], $this->me['user_id'], null, $price_types[$price_mode])
	    				->setWordsPrice($recommend_words, $params['max_price'] * 100);
        	}
        }
        
        $max_competition = 0;
        $tmp_words = array();
        foreach($recommend_words as $k=>$w){
            $recommend_words[$k]['word'] = $w['word'] ? $w['word'] : $k;
            $recommend_words[$k]['trend'] = ''; //implode( "," , $trend );
          //  $tmp = floatval( $recommend_words[$k]['competition'] );
           // $max_competition = $tmp && $max_competition < $tmp ? $tmp : $max_competition;
           if($price_mode == 0) {
           		$rec_price = floatval( $recommend_words[$k]["avg_price"] ) * floatval( $price_set );
           }else{
           		$rec_price = $wordsPrice[$recommend_words[$k]['word']]['max_price'];
           }
            $rec_price = $rec_price < 6 ? 6 : 
            		($rec_price > $params['max_price'] && $params['max_price'] > 6 ? $params['max_price'] : $rec_price);
            $recommend_words[$k]["max_price"] = round( $rec_price / 100.0 , 2 );
            $recommend_words[$k]["avg_price"] = isset($recommend_words[$k]["avg_price"]) ? $recommend_words[$k]["avg_price"] / 100.0 : 0;
        }
        
        // 计算竞争度条的长度
        import('@.Library.Carine');
   		$carine = new Carine();
    	$boundary = $carine->getBondary($params['category_id']);
    	$max_competition = isset( $boundary['competition'] ) ? $boundary['competition']['max'] : $max_competition;
    	//get the trends of each word
    	//$trends = $carine->getTrendofWords($tmp_words);
        foreach($recommend_words as &$w){
            $w["width"] =  isset($w["competition"]) ? ceil ( ( 1.0 * $w["competition"] / $max_competition) * 100  ) : 0;
            $w["width"] =  $w["width"] > 100 ? 100 :  $w["width"];
        }
        
        
        $this->words = $recommend_words;
        $this->words_count = count($recommend_words);
        // 
        if(empty($recommend_words)) {
        	if($params["searchMode"] == '#manual' && empty($params['mykeywords'])) {
        		$this->msg = '请在右边输入关键词查询';
        	} else {
        		$this->msg = '对不起, 没有找到合适的关键词';
        	}
        }
        $this->display();
    }
    
    /**
     * 组合词
     * @param array(k=>v) $params
     * @return multitype:|Ambigous <mixed, void, unknown>
     */
    protected function combineKeywords($params){
        $keywordMdl = new KeywordModel();
       	$mykeywords = $params['mykeywords'];
       	foreach($mykeywords as &$mykeyword){
       		$mykeyword=trim($mykeyword);
       	}
       	$mykeywords=array_unique($mykeywords);
//        	junky_words_cleaner($mykeywords);
        if(empty($mykeywords)){
            return array();
        }
        $cacheKey =  md5( implode('',$mykeywords) . $this->me['user_id'] . 'combination' );
        $keywords = S($cacheKey);
        if(empty($keywords)){
            $productMdl = new ProductModel();
            if( count($mykeywords) >= 2){
                $combined_words = $productMdl->combineWords( $mykeywords, 3);
                $mykeywords = array_merge( $combined_words, $mykeywords);
            } 
            $mykeywords = array_flip($mykeywords);
            $keywords = $this->getStatsOfWords($mykeywords);
            //cache for 10 mins
            S( $cacheKey , $keywords , 600);
        }
   		return $keywords;
    }
    
    /**
     * 查找相关词
     * @param array(k=>v) $params
     * @return multitype:|Ambigous <mixed, void, unknown>
     */
    protected function findRelatedKeywords($params){
        $keywordMdl = new KeywordModel();
        $mykeywords = $params['mykeywords'];
//         junky_words_cleaner($mykeywords);
        if(empty($mykeywords)){
            return array();
        }
        $cacheKey = md5( implode('', $mykeywords) . $this->me['user_id'] . 'related'  );
        $keywords = S($cacheKey);
        if(empty($keywords)){
            $wordMdl = new WordModel();
            $related_words = $wordMdl->getRelatedWords( $mykeywords , true ,true);
            $related_words = array_flip($related_words);
            $keywords = $this->getStatsOfWords($related_words);
            S( $cacheKey , $keywords , 600);
        }
        return $keywords;
    }
    
    
    /**
     * 复制关键词
     * @param array(k=>v) $params
     * @return multitype:|mixed
     */
    protected function copyKeywords( $params ){
        $copyfrom = $params['copyfrom'];
        if( ! $copyfrom ){
            return array();
        } 
        $keywordMdl = new KeywordModel();
        $whr = array(
            'user_id' => $this->me['user_id'],
            'adgroup_id' => $copyfrom
        );
        $keywords = $keywordMdl->where(  $whr  )->select();
        $keywords = $this->getStatsOfWords($keywords);
        return $keywords;
    }
    
    
    public function listadgroups(){
        $page = $this->_get('page');
        $pageSize = $this->_get('pageSize');
        $keyword = $this->_get('keyword');
        $adgroupMdl = M('adgroups');
        $whr = array(
            'user_id' => $this->me['user_id']
        ); 
        if($keyword){
            $whr['title'] = array( 'like' ,'%' . $keyword . '%');
        }
        $adgroups = $adgroupMdl->where($whr)->page($page)->limit($pageSize)->select();
        $more = $adgroupMdl->where($whr)->page($page)->limit($pageSize)->count();
        $res = array(
            'nextpage' => $more > 0 ? true : false,
        	'currentPage' => $page,
            'keyword' => $keyword,
            'adgroups' => $adgroups
        );
        $this->display_json( $res );
    }
    
    /**
     * 手动加词
     * @param array(k=>v) $params
     * @return multitype:|mixed
     */
    protected function manualKeywords( $params ){
        $keywordMdl = new KeywordModel();
       	$mykeywords = $params['mykeywords'];
        if(!$mykeywords){
            return array();
        }
//         junky_words_cleaner( $mykeywords );
        $mykeywords = array_flip($mykeywords);
        $keywords = $this->getStatsOfWords($mykeywords);
   		return $keywords;
    }
    
    /**
     * 我的词库(get the keywords of user saved). 
     * @param array(k=>v) $params
     */
    public function findMyKeywords( $params ){
   		$keywordMdl = M('mykeyword');
   		$page = $params['currentPage'];
   		$page_size = $params['pageSize'];
		$mykeywords = $params['mykeywords'] ? explode(' ',$params['mykeywords']) : array();
		$words = array();
		foreach($mykeywords as &$w){
			if($w){
				$search_keywords[] = $w . '%' ;
				$words[] = $w;
			}
		}
		
		$filterType = intval( $params['filterType'] );
		$like = $filterType ? 'like' : 'notlike';
		$map['user_id'] = $this->me['user_id'];
        $and = $filterType ? 'OR' : 'AND';
		if( !empty($mykeywords) ) $map['word'] = array( $like , $search_keywords , $and);
   		$keywords = $keywordMdl->where( $map )->field( 'word' )->select();
   		if($keywords)
        	$keywords = $this->getStatsOfWords($keywords);
   		return $keywords;   		
    }
    
    /** 关键词改价历史 */
    public function log(){
    	$adgroup_id = $this->_request('adgroup_id');
    	$keyword_id = $this->_request('keyword_id');
    	//得到关键词的历史表现数据
    	$rptMdl = new RptKeywordModel();
    	// try to get the min date of keyword 
    	$min_date = $rptMdl->where( 'keyword_id=' . $keyword_id )->min('date');
    	$from = max( $min_date,  date('Y-m-d' , date2time(-30)) ); 
    	$to = date('Y-m-d' , date2time(-1));
    	$stats = $rptMdl->getStats($this->me['user_id'], $keyword_id , 'roi,impressions,click,ctr,sales,cost,cpc', $from , $to);
    	$keywordMdl = new KeywordModel();
    	$logs = $keywordMdl->getLogs( $this->me['user_id'], 'keyword_id' , $keyword_id, null, null, true );
        $stats['keyword'] = M('keywords'.$this->me['user_id'])->where('keyword_id = '. $keyword_id)->getField('word');
    	$stats['logs'] = $logs;
    	$this->display_json($stats);
    }
    
    
    /** 关键词自动调价的log ， 仅admin可以访问 */
    
    public function autolog(){
    	$is_admin =  session('admin');
    	if( empty( $is_admin ) ){
    		throw new NewzanException('你无权访问此页面' , RetStatus::INNER_ERR);
    	}
    	
    	$adgroup_id = $this->_get('adgroup_id');
    	$keyword_id = $this->_get('keyword_id');
    	
    	if(empty($adgroup_id) && empty($keyword_id)){
    		throw new NewzanException( '推广组id或者关键词id至少输入一个' , RetStatus::PARAM_ERR);
    	}
    	
    	$autoMdl = M('auto_maintain_log');
    	//如果有keyword_id读取该keyword_id的所有log
    	if( $keyword_id ){
    		$whr['keyword_id'] = $keyword_id;
    	}else{
    		$whr['adgroup_id'] = $adgroup_id;
    	}
		$logs = $autoMdl->where($whr)->select();
		
		
		$keywordMdl = new KeywordModel();
		$action_names = array(
				AutoMaintainLogActions::NO_CHANGE => array( 'name' => '无操作', 'css' => ''),
				AutoMaintainLogActions::DEC_PRICE => array( 'name' => '降低价格', 'css' => 'label-info'),
				AutoMaintainLogActions::DEC_PRICE_NOT_FULL => array( 'name' => '非完全降价', 'css' => 'label-info'),
				AutoMaintainLogActions::DEL_WORD => array( 'name' => '删除', 'css' => 'label-important'),
				AutoMaintainLogActions::INC_PRICE => array( 'name' => '提高价格', 'css' => 'label-success'),
				AutoMaintainLogActions::INC_PRICE_NOT_FULL => array( 'name' => '非完全加价', 'css' => 'label-success'),
				AutoMaintainLogActions::DEC_PRICE_TO_MAX_ALLOWED => array( 'name' => '降至最高允许价格', 'css' => 'label-info'),
		);
		//read the logs
		$status_descriptions = AutoDriveV2Model::$STATUS_DESC;
		if($logs) {
			foreach($logs as &$log){
				//read actions to meaningful strs
				$action_status =  substr( $log['action'] ,0,4);
				$action_plan = substr($log['action'] , 4, 1);
				$action_did = substr($log['action'] , 5, 1);
				if($action_did !== false){	
					$log['action_done'] = $action_names[ $action_did ];
				}else{
					$log['action_done'] = '无法解析的action字符串:' . $log['action'];
				}
				
				if($action_plan !== false){
					$log['action_plan'] = $action_names[ $action_plan ];
				}else{
					$log['action_plan'] = '无法解析的action字符串:' . $log['action'];
				}			
	
				if($action_status !== false){
					$log['action_status'] = isset($status_descriptions[ $action_status ]) ?  $status_descriptions[ $action_status ] : "不识别的状态码:" . $action_status;
				}else{
					$log['action_status'] = '无法解析的action字符串:' . $log['action'];
				}
			}
		}
		$this->logs = $logs;
		$this->word = $keywordMdl->where(array('keyword_id' => $keyword_id))->getField('word');
		if(!$this->word) 
			$this->word = M('keywords_deleted')->where(array('keyword_id' => $keyword_id))->getField('word');
		$this->display();
    }
    	
    protected function getStatsOfWords($words){
        $tmp_words = array();
        foreach($words as $k=>$w){
            $tmp_words[] = $w['word'] ? $w['word'] : $k;
        }
		import('@.Library.Carine');
   		$carine = new Carine();
   		$result = $carine->getStatofWords( $tmp_words );
   		$result = json_decode($result , true);
   		$stats = $result['response'];
   		$words_with_stats = array();
        foreach( $stats as $key => &$word){
            $word['word']  = $key;
       	}
       	return $stats;
    }

    /**
     * 获取关键词的市场数据(全网数据) 展现量、点击率、点击转化率等
     * @param  array        $keywords           关键词 必须是数组
     * @return array        $return_data        返回的数据
     */
    private function getMarket($keywords)
    {
        $check_data = array('impression','coverage','cpc','roi','competition');
        
        $wordMdl = new WordModel();
        $return_data = $wordMdl->getAvgProps($keywords, 'pv,click,ctr,competition,avg_price', strtotime($start_time), strtotime($end_time), true);
        foreach ($return_data as $key => $d) {
            foreach($check_data as $c) {
                if(!isset($d['effect'][$c])) {
                    $return_data[$key]['effect'][$c] = 0;
                }
            }
        }
        $keyword_id = array_keys($return_data);
        // 更新session 中的全网数据
        $s_name = 'marketdata_'.$this->me['user_id'];
        if(session("?{$s_name}")) {
            $tmp = session($s_name);
            $tmp_keyword_id = array_keys($tmp);
            if($keyword_id) {
                foreach ($keyword_id as $key => $id) {
                    if(!in_array($id, $tmp_keyword_id)) {
                        $tmp[$id] = $return_data[$id];
                    }
                }
                session($s_name, $tmp);
            }
        } else {
            session($s_name, $return_data);
        }

        return $return_data;
        // $this->display_json($return_data);
    }

    /**
     * 获取关键词的市场数据Action
     * @return [type] [description]
     */
    public function marketdata()
    {
        $keywords = $_POST['keywords'];
        $return_data = $this->getMarket($keywords);
        $this->display_json($return_data);
    }


    /**
     * @return AutoDriveBaseModel
     */
    private function _getAutoDriveMdl() {
    	if($this->_autoDriveMdl === null) {
    		$autoDriveMdlClass = 'AutoDrive' . DEFAULT_AUTO_ENGINE . 'Model';
    		$this->_autoDriveMdl = new $autoDriveMdlClass();
    	}
    	return $this->_autoDriveMdl;
    }
    
    
}
